import { shallowEqualApp, useAppSelector } from '@/Hooks/hook'
import { memo, useRef, useState } from 'react'
import type { ReactNode, FC, ComponentRef } from 'react'
import { BannerControl, BannerLeft, BannerRight, BannerWrapper } from './style'
import { Carousel } from 'antd'
import classNames from 'classnames'

interface IProps {
  children?: ReactNode
}

const TopBanner: FC<IProps> = () => {
  //定义内部的数据
  const [currentIndex, setCurrentIndex] = useState(0)
  const bannerRef = useRef<ComponentRef<typeof Carousel>>(null)
  //store里面获取数据
  const { banners } = useAppSelector(
    (state) => ({
      banners: state.recommend.banners
    }),
    shallowEqualApp
  )

  //切换图片后处理函数
  const handleAfterChange = (current: number) => {
    // console.log(current)
    setCurrentIndex(current)
  }

  //切换上一张图片
  const handlePreClick = () => {
    bannerRef.current?.prev()
  }
  //切换下一张图片
  const handleNextClick = () => {
    bannerRef.current?.next()
  }
  //获取背景图片
  let bgImageUrl
  if (currentIndex >= 0 && banners.length > 0) {
    bgImageUrl = banners[currentIndex].imageUrl + '?imageView&blur=40x20'
  }

  return (
    <div>
      <BannerWrapper
        style={{ background: `url('${bgImageUrl}') center center /6000px` }}
      >
        <div className="banner wrap-v2">
          <BannerLeft>
            {/* 轮播图 */}
            <Carousel
              autoplay
              effect="fade"
              ref={bannerRef}
              afterChange={handleAfterChange}
              dots={false}
            >
              {banners.map((item: any) => {
                return (
                  <div className="banner-item" key={item.imageUrl}>
                    <img
                      className="image"
                      src={item.imageUrl}
                      alt={item.title}
                    />
                  </div>
                )
              })}
            </Carousel>
            {/* 自定义轮播图下标 */}
            <ul className="dots">
              {banners.map((item: any, index: number) => {
                return (
                  <li key={item.imageUrl}>
                    <span
                      className={classNames('item', {
                        active: index === currentIndex
                      })}
                    ></span>
                  </li>
                )
              })}
            </ul>
          </BannerLeft>
          <BannerRight></BannerRight>
          <BannerControl>
            <button className="btn left" onClick={handlePreClick}></button>
            <button className="btn right" onClick={handleNextClick}></button>
          </BannerControl>
        </div>
      </BannerWrapper>
    </div>
  )
}

export default memo(TopBanner)
